package src

import (
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

type person struct {
	Id      int    `form:"-"`
	Title   string `form:"title" binding:"len_valid"` // 不能为空    omitempty,  min=5
	Content string `form:"content" binding:"min=5"`
	Desc    string `form:"desc"`
	//Uid     []User `binding:"required,dive,min=10"`
	//Name    [][]int `binding:"min=10,dive,max=20,dive,required"`
	//Name [][]int `binding:"dive,max=20,dive,required"`
}

func ToValidDate(ctx *gin.Context) {

	ctx.HTML(http.StatusOK, "chapter/valid_data.html", nil)
}

func DoValidDate(ctx *gin.Context) {
	var person person
	err := ctx.ShouldBind(&person)
	fmt.Println(err)
	fmt.Println(person)
	if err != nil {
		ctx.String(http.StatusOK, "验证失败: %+v, Error: %s", person, err)
	} else {
		ctx.String(http.StatusOK, "验证成功: %+v", person)
	}

}

// 判断是不是大于6
var LenValid validator.Func = func(fl validator.FieldLevel) bool {
	data := fl.Field().Interface().(string)
	if len(data) > 6 {
		fmt.Println("false")
		return false
	} else {
		fmt.Println("true")
		return true
	}
}

type Person struct {
	Id    int    `form:"-"`
	Name  string `form:"name" valid:"Required"`
	Age   int    `form:"age"  valid:"Range(0, 999)"`
	Hobby string `form:"hobby" valid:"Length(2)"`
}

// beego
func DoValidDate2(ctx *gin.Context) {
	var person Person
	err := ctx.ShouldBind(&person)
	fmt.Println(err)
	fmt.Println(person)

	//重写错误信息：validation.SetDefaultMessage(map)
	var Messages = map[string]string{
		"Required": "不能为空",
		"MinSize":  "最短长度为 %d",
		"Length":   "长度必须为 %d",
		"Numeric":  "必须是有效的数字",
		"Email":    "必须是有效的电子邮件地址",
		"Mobile":   "必须是有效的手机号码",
		"Range":    "范围必须在0-999之间",
	}

	validation.SetDefaultMessage(Messages)
	// 初始化验证器
	valid := validation.Validation{}
	// 校验
	b, errl := valid.Valid(&person)
	fmt.Println(errl)

	fmt.Printf("%+T", person.Age)
	fmt.Println("")
	//
	key_mapping := map[string]interface{}{
		"Name.Required.": "名字",
		"Age.Range.":     "年齡",
		"Hobby.Length.":  "愛好",
	}

	if !b {
		// 校验有误
		for _, err2 := range valid.Errors {
			fmt.Println(err2.Key)
			fmt.Println(err2.Message)
			key := key_mapping[err2.Key]
			ctx.String(http.StatusOK, key.(string)+err2.Message+"\n")
		}
	} else {
		ctx.String(http.StatusOK, "验证成功: %+v", person)
	}

	//if err != nil {
	//	ctx.String(http.StatusOK, "验证失败: %+v, Error: %s", person, err)
	//} else {
	//	ctx.String(http.StatusOK, "验证成功: %+v", person)
	//}

}
